<script setup lang="ts">
import { computed, ref } from 'vue';

import { FireOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { marked } from 'marked';

import { zhuMembers } from '../../../mock/zhu-dynasty/members';

interface AncestorData {
  id: string;
  name: string;
  title: string;
  avatar: string;
  birthDate: string;
  deathDate: string;
  reignPeriod?: string;
  bio: string;
  biography: string;
  flowerCount: number;
  messageCount: number;
  video?: string;
  audio?: string;
}

const memorialModalVisible = ref(false);
const selectedAncestor = ref<AncestorData | null>(null);
const newMessage = ref('');

// 已故祖先列表
const ancestors = computed(() => {
  return zhuMembers
    .filter((m) => m.deathDate)
    .map((m) => ({
      ...m,
      bio: m.achievements.join('、'),
      biography: `## ${m.title}\n\n${m.name}（${m.birthDate} - ${m.deathDate}）\n\n${m.achievements.map((a) => `- ${a}`).join('\n')}`,
      flowerCount: Math.floor(Math.random() * 500) + 100,
      messageCount: Math.floor(Math.random() * 200) + 50,
    }));
});

const memorialMessages = ref([
  {
    id: 1,
    userName: '朱瞻基',
    userAvatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=ZhuZhanji',
    content: '追思太祖高皇帝创业之艰，愿世代子孙铭记先祖功德！',
    time: '2025-01-15T10:00:00Z',
    onChain: true,
  },
  {
    id: 2,
    userName: '朱棣',
    userAvatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=ZhuDi',
    content: '父皇在天之灵，请庇佑大明江山永固！',
    time: '2025-01-10T14:30:00Z',
    onChain: true,
  },
]);

const flowerTypes = [
  { type: 'chrysanthemum', icon: '🌼', name: '菊花' },
  { type: 'lily', icon: '🌸', name: '百合' },
  { type: 'rose', icon: '🌹', name: '玫瑰' },
  { type: 'orchid', icon: '🌺', name: '兰花' },
];

function openMemorial(ancestor: any) {
  selectedAncestor.value = ancestor;
  memorialModalVisible.value = true;
}

function renderMarkdown(text: string) {
  return marked(text);
}

function formatTime(time: string) {
  return dayjs(time).format('YYYY-MM-DD HH:mm');
}

function submitMessage() {
  if (!newMessage.value.trim()) {
    message.warning('请输入留言内容');
    return;
  }

  message.loading('正在上链存证...', 2);
  setTimeout(() => {
    memorialMessages.value.unshift({
      id: Date.now(),
      userName: '当前用户',
      userAvatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Current',
      content: newMessage.value,
      time: new Date().toISOString(),
      onChain: true,
    });
    message.success('留言已上链！');
    newMessage.value = '';
  }, 2000);
}

function offerFlower(flower: any) {
  message.loading(`正在献上${flower.name}...`, 2);
  setTimeout(() => {
    if (selectedAncestor.value) {
      selectedAncestor.value.flowerCount++;
    }
    message.success(`献花成功！已生成链上存证，祭礼SBT正在铸造...`);
  }, 2000);
}
</script>

<template>
  <div class="ancestor-memorial">
    <!-- 纪念堂头部 -->
    <a-card class="memorial-header">
      <div class="header-content">
        <h1>🕯️ 朱氏祖先纪念堂</h1>
        <p>慎终追远，民德归厚</p>
      </div>
    </a-card>

    <!-- 祖先列表 -->
    <a-row :gutter="16" style="margin-top: 16px">
      <a-col
        v-for="ancestor in ancestors"
        :key="ancestor.id"
        :span="8"
        style="margin-bottom: 16px"
      >
        <a-card hoverable @click="openMemorial(ancestor)">
          <div class="ancestor-card">
            <div class="ancestor-photo">
              <img :src="ancestor.avatar" :alt="ancestor.name" />
              <div class="memorial-tag">
                <FireOutlined /> {{ ancestor.title }}
              </div>
            </div>
            <div class="ancestor-info">
              <h3>{{ ancestor.name }}</h3>
              <p class="life-span">
                {{ ancestor.birthDate }} - {{ ancestor.deathDate }}
              </p>
              <p class="bio">{{ ancestor.bio }}</p>
              <a-space style="margin-top: 12px">
                <a-statistic
                  title="献花"
                  :value="ancestor.flowerCount"
                  suffix="朵"
                  :value-style="{ fontSize: '14px' }"
                />
                <a-statistic
                  title="留言"
                  :value="ancestor.messageCount"
                  suffix="条"
                  :value-style="{ fontSize: '14px' }"
                />
              </a-space>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 纪念详情Modal -->
    <a-modal
      v-model:open="memorialModalVisible"
      :title="`${selectedAncestor?.name} 纪念馆`"
      width="900px"
      :footer="null"
    >
      <div v-if="selectedAncestor" class="memorial-detail">
        <a-row :gutter="24">
          <a-col :span="10">
            <div class="ancestor-portrait">
              <img
                :src="selectedAncestor.avatar"
                :alt="selectedAncestor.name"
              />
            </div>
            <a-descriptions
              :column="1"
              bordered
              size="small"
              style="margin-top: 16px"
            >
              <a-descriptions-item label="姓名">
                {{ selectedAncestor.name }}
              </a-descriptions-item>
              <a-descriptions-item label="谥号">
                {{ selectedAncestor.title }}
              </a-descriptions-item>
              <a-descriptions-item label="生辰">
                {{ selectedAncestor.birthDate }}
              </a-descriptions-item>
              <a-descriptions-item label="忌日">
                {{ selectedAncestor.deathDate }}
              </a-descriptions-item>
              <a-descriptions-item label="在位">
                {{ selectedAncestor.reignPeriod || '-' }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :span="14">
            <a-tabs>
              <a-tab-pane key="bio" tab="生平简介">
                <div
                  class="bio-content"
                  v-html="renderMarkdown(selectedAncestor.biography)"
                ></div>
              </a-tab-pane>
              <a-tab-pane key="media" tab="缅怀音视频">
                <div class="media-gallery">
                  <video
                    v-if="selectedAncestor.video"
                    controls
                    style="width: 100%"
                  >
                    <source :src="selectedAncestor.video" type="video/mp4" />
                  </video>
                  <audio
                    v-if="selectedAncestor.audio"
                    controls
                    style="width: 100%; margin-top: 16px"
                  >
                    <source :src="selectedAncestor.audio" type="audio/mp3" />
                  </audio>
                </div>
              </a-tab-pane>
              <a-tab-pane key="messages" tab="留言板">
                <div class="messages-section">
                  <a-list :data-source="memorialMessages" size="small">
                    <template #renderItem="{ item }">
                      <a-list-item>
                        <a-list-item-meta>
                          <template #avatar>
                            <a-avatar :src="item.userAvatar" />
                          </template>
                          <template #title>
                            {{ item.userName }}
                            <a-tag
                              v-if="item.onChain"
                              color="green"
                              size="small"
                            >
                              已上链
                            </a-tag>
                          </template>
                          <template #description>
                            {{ item.content }}
                          </template>
                        </a-list-item-meta>
                        <div class="message-time">
                          {{ formatTime(item.time) }}
                        </div>
                      </a-list-item>
                    </template>
                  </a-list>
                  <a-textarea
                    v-model:value="newMessage"
                    placeholder="写下对先祖的缅怀..."
                    :rows="3"
                    style="margin-top: 16px"
                  />
                  <a-button
                    type="primary"
                    @click="submitMessage"
                    style="margin-top: 8px"
                  >
                    提交留言并上链
                  </a-button>
                </div>
              </a-tab-pane>
            </a-tabs>
          </a-col>
        </a-row>

        <a-divider />

        <!-- 祭拜功能 -->
        <div class="worship-section">
          <h3>🕯️ 虚拟献花</h3>
          <a-space size="large" style="margin-top: 16px">
            <div
              v-for="flower in flowerTypes"
              :key="flower.type"
              class="flower-option"
              @click="offerFlower(flower)"
            >
              <div class="flower-icon">{{ flower.icon }}</div>
              <div class="flower-name">{{ flower.name }}</div>
            </div>
          </a-space>
          <a-alert
            message="献花将生成链上存证，并铸造'祭礼SBT'作为永久纪念"
            type="info"
            show-icon
            style="margin-top: 16px"
          />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<style scoped lang="scss">
.ancestor-memorial {
  .memorial-header {
    color: white;
    text-align: center;
    background: linear-gradient(135deg, #8b4513 0%, #a0522d 100%);

    .header-content {
      padding: 24px;

      h1 {
        margin: 0 0 8px;
        font-size: 28px;
        color: white;
      }

      p {
        margin: 0;
        opacity: 0.9;
      }
    }
  }

  .ancestor-card {
    .ancestor-photo {
      position: relative;
      margin-bottom: 16px;

      img {
        width: 100%;
        height: 200px;
        object-fit: cover;
        border-radius: 8px;
        filter: grayscale(30%);
      }

      .memorial-tag {
        position: absolute;
        bottom: 8px;
        left: 8px;
        padding: 4px 12px;
        font-size: 12px;
        color: white;
        background: rgb(139 69 19 / 90%);
        border-radius: 4px;
      }
    }

    .ancestor-info {
      h3 {
        margin: 0 0 8px;
        font-size: 18px;
      }

      .life-span {
        margin: 0 0 8px;
        font-size: 13px;
        color: #999;
      }

      .bio {
        margin: 0 0 12px;
        font-size: 14px;
        line-height: 1.6;
        color: #666;
      }
    }
  }

  .memorial-detail {
    .ancestor-portrait {
      img {
        width: 100%;
        border-radius: 8px;
        filter: grayscale(20%);
      }
    }

    .bio-content {
      line-height: 1.8;
      color: #666;

      h2 {
        margin-bottom: 12px;
        font-size: 18px;
      }

      ul,
      li {
        margin-left: 20px;
      }
    }

    .media-gallery {
      video,
      audio {
        border-radius: 8px;
      }
    }

    .messages-section {
      max-height: 400px;
      overflow-y: auto;

      .message-time {
        font-size: 12px;
        color: #999;
      }
    }

    .worship-section {
      h3 {
        margin-bottom: 16px;
      }

      .flower-option {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 16px;
        cursor: pointer;
        border: 2px solid #f0f0f0;
        border-radius: 8px;
        transition: all 0.3s;

        &:hover {
          background: #fff8f0;
          border-color: #a0522d;
          transform: translateY(-4px);
        }

        .flower-icon {
          margin-bottom: 8px;
          font-size: 48px;
        }

        .flower-name {
          font-size: 14px;
          color: #666;
        }
      }
    }
  }
}
</style>
